const express = require('express');
const pool = require("../db");
const Petmsg = express.Router();

// 宠物百科
Petmsg.get('/', (req, res, next) => {
	pool.query('select * from petmessage', (err, results) => {
		if (err) {
			//如果SQL中出现错误，交给下一个错误处理中间件
			//阻止往后执行
			return next(err)
		}
		console.log(results)
		if (results.length === 0) {
			res.send({ code: 400, msg: '暂无领养动物' })
		} else {
			res.send({ code: 200, msg: '查询成功', data: results })
		}
	})
})

// 宠物百科详情页接口 /petmessage/details?pmid=
Petmsg.get('/details', (req, res, next) => {
	var obj = req.query.pmid
	console.log(obj);
	pool.query('select * from petmessage where pmid=?', [obj], (err, results) => {
		if (err) {
			//如果SQL中出现错误，交给下一个错误处理中间件
			//阻止往后执行
			return next(err)
		}
		if (results.length === 0) {
			res.send({ code: 400, msg: '暂无领养动物' })
		} else {
			res.send({ code: 200, msg: '查询成功', results: results })
		}
	})
})

// 搜索接口  /petmessage/search?msg=
Petmsg.get('/search', (req, res, next) => {
	let obj = req.query.msg
	console.log(obj);
	pool.query('select * from petmessage where petName like ?', [`%${obj}%`], (err, results) => {
		if (err) {
			//如果SQL中出现错误，交给下一个错误处理中间件
			//阻止往后执行
			return next(err)
		}
		if (results.length === 0) {
			res.send({ code: 400, msg: '暂无' })
		} else {
			res.send({ code: 200, msg: '查询成功', data: results })
		}
	})
})

// 分类接口
Petmsg.post('/type', (req, res, next) => {
	let obj = req.body
	pool.query('select * from petmessage where petType=?', [obj.petType], (err, results) => {
		if (err) {
			//如果SQL中出现错误，交给下一个错误处理中间件
			//阻止往后执行
			return next(err)
		}
		console.log(results);
		if (results.length === 0) {
			res.send({ code: 201, msg: '暂无' })
		} else {
			res.send({ code: 200, msg: '查询成功', data: results })
		}
	})
})

module.exports = Petmsg